<?php

/**
 * URL管理类
 * 
 * @author keluo<pycorvn@yeah.net>
 * @since 2015-01-24
 */
class SCUrl {
    
    /**
     * 项目web根目录
     * @var string
     */
    public $base;
    
    /**
     * 项目web根目录绝对路径
     * @var string
     */
    public $absoluteBase;
    
    public function __construct() {
        $this->base = SCS::request()->baseURI;
        $this->absoluteBase = 'http://'.$_SERVER['HTTP_HOST'].$this->base;
    }
    
    /**
     * 根据路由生成完整URL
     * @param string $route
     * @param mixed $params url中请求参数
     * @param boolean $absolute 是否生成绝对路径
     * @return string
     * @example
     * <pre>
     * $url = SCS::url()->create('control/action', array('a' => '1', 'b' => '你好'));
     * $url = SCS::url()->create('control/action', 'a/1/b/你好'); // control/action/a/1/b/你好
     * $url = SCS::url()->create('control', 'a/1/b/你好'); // control/index/a/1/b/你好
     * $url = SCS::url()->create(null, 'a/1/b/你好'); // index/index/a/1/b/你好
     */
    public function create($route = '', $params = null, $absolute = false, $space = '+') {
        $baseUri = $absolute ? $this->absoluteBase : $this->base;
        if(!$route) return $baseUri.'/';
        $route = explode('/', trim($route));
        $control = (isset($route[0]) && strlen($route[0])) ? $route[0] : ($params ? 'index' : '');
        $action = (isset($route[1]) && strlen($route[1])) ? $route[1] : ($params ? 'index' : '');
        $route = $control.'/'.$action;
        if(is_array($params)) {
            $queryString = '';
            foreach($params as $key=>$value) {
                $queryString .= $key.'/'.urlencode($value).'/';
            }    
        } else {
            $queryString = $params;
        }
        if($space) {
        	$queryString = preg_replace('/\s+/', $space, $queryString);
        }
        return rtrim($baseUri.(SCS::config()->rewrite ? '/' : '/?').$route.'/'.$queryString, '/');
    }
    
    /**
     * 基本路径上翻路径
     * @param number $level
     * @param boolean $absolute 是否使用绝对路径
     * @return string
     */
    public function upper($level = 1, $absolute = true) {
        $parent = $absolute ? $this->absoluteBase : $this->base;
        for($i = 0; $i < $level; $i++) {
            $parent = rtrim(dirname($parent), '/');
        }
        return $parent;
    }
}